#include "itemwindow.h"
#include "ui_itemwindow.h"

ItemWindow::ItemWindow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ItemWindow)
{
    ui->setupUi(this);
    initTable();
}

ItemWindow::~ItemWindow()
{
    delete ui;
}

void ItemWindow::initTable()
{
    QStringList headers;
    headers<<"id"<<"name"<<"time";
    //ui->tableWidget->setRowCount(10);

    //设置表头的列数
    ui->tableWidget->setColumnCount(headers.size());
    ui->tableWidget->setHorizontalHeaderLabels(headers);
    //设置表头
    QTableWidgetItem *newItem = new QTableWidgetItem("1");
    ui->tableWidget->setItem(0, 0, newItem);
}

void ItemWindow::on_addPushButton_clicked()
{
    //添加设备，弹出设备对话框
    DeviceInfoDialog *dlg = new DeviceInfoDialog;

    //设置窗口属性，关闭窗口时资源回收
    dlg->setAttribute(Qt::WA_DeleteOnClose);

    connect(dlg,&DeviceInfoDialog::sentDeviceInfoDialog,this,[=](QString name,QString time,QString id){
        qDebug()<<name<<" "<<time<<" "<<id;

        //获取表格当前的行数
        int rows = ui->tableWidget->rowCount();
        ui->tableWidget->insertRow(rows);

        ui->tableWidget->setItem(0, 0, new QTableWidgetItem(id));
        ui->tableWidget->setItem(0, 1, new QTableWidgetItem(name));
        ui->tableWidget->setItem(0, 2, new QTableWidgetItem(time));
    });
    dlg->show();
}


void ItemWindow::on_savepPushButton_clicked()
{
    int rows = ui->tableWidget->rowCount();
    int cols = ui->tableWidget->columnCount();

    //遍历表格数据,将表格数据保存到.csv文件中
    QFile file(QFileDialog::getSaveFileName(this,"save data",".","excel(*.csv)"));
    QString lines;

    file.open(QIODevice::WriteOnly);
    for(int i = 0; i < rows; i++)
    {
        for(int j = 0; j < cols; j++)
        {
            lines += ui->tableWidget->item(i,j)->text()+ ",";
        }
        //去掉最后一个","分隔符
        lines.chop(1);
        lines += "\r\n";
        file.write(lines.toUtf8());
        lines.clear();
    }
    file.close();

}

//删除数据
void ItemWindow::on_delPushButton_clicked()
{
    //删除所有数据，保留表头和表格
    //ui->tableWidget->clearContents();

    int curRow = ui->tableWidget->currentRow();
    if(curRow == -1)
    {
        QMessageBox::warning(this,"删除行","请选中有效的行进行删除操作",QMessageBox::Ok);
        return;
    }
    ui->tableWidget->removeRow(curRow);
}

void ItemWindow::on_tableWidget_clicked(const QModelIndex &index)
{
    ui->tableWidget->selectRow(index.row());
}
